<?php

namespace frontend\modules\resource\logic;


use common\models\BasMember;
use common\models\UserBranch;
use frontend\modules\common\models\BaseHelper;
use frontend\modules\common\models\ExcelReader;
use Yii;
use yii\db\Exception;
use yii\web\NotFoundHttpException;


/**
 * BranchSearch represents the model behind the search form of `common\models\Branch`.
 */
class UserBranchLogic
{

    /**
     * @param $id
     * @param $branchId
     * @return bool
     * @throws \yii\base\ExitException
     */
    public function UpdateUserStatus($id, $branchId)
    {
        if (!is_numeric($id))
            BaseHelper::Error('参数格式有误');
        $model = UserBranch::find()->where(['user_id' => $id, 'br_id' => $branchId])->one();
        if (empty($model))
            BaseHelper::Error('没有找到对应记录');
        $model->status = !$model->status;
        return $model->save(false);
    }

    /**
     * @param $id
     * @param $branchId
     * @return false|int
     * @throws \Throwable
     * @throws \yii\base\ExitException
     * @throws \yii\db\StaleObjectException
     */
    public function RemoveUser($id, $branchId)
    {
        if (!is_numeric($id))
            BaseHelper::Error('参数格式有误');
        $model = UserBranch::find()->where(['user_id' => $id, 'br_id' => $branchId])->one();
        if (empty($model))
            BaseHelper::Error('没有找到对应记录');
        return $model->delete();
    }


    /**
     * @param $path
     * @param $excelHeader
     * @param $brId
     * @param $branchTitle
     * @return int
     * @throws Exception
     * @throws \PHPExcel_Exception
     * @throws \PHPExcel_Reader_Exception
     * @throws \yii\base\ExitException
     * 读取插入用户信息
     */
    public function ImportData($path, $excelHeader, $brId, $branchTitle)
    {

        if (!file_exists($path)) {
            BaseHelper::Error('文件不存在');
        }
        //设置脚本运行时间（单位：秒） 0-没有时间限制
        set_time_limit(0);
        //memory_limit-设定一个脚本所能够申请到的最大内存字节数
        ini_set('memory_limit', '256M');
        $data = (new ExcelReader())->NormalReadExcel($path, $excelHeader);
        unset($data[0]);
        //校验字段是否都符合todo
        $num = $this->_insertUserData($data, $brId, $branchTitle);
        return $num;
    }

    /**
     * 插入数据
     * @param $data
     * @param $brId
     * @param $branchTitle
     * @return int
     * @throws Exception
     * @throws \yii\base\ExitException
     */
    private function _insertUserData($data, $brId, $branchTitle)
    {

//        $data = [
//            ['phone' => '15234143', 'user_name' => 'ddada', 'id_number' => ''],
//            ['phone' => '15234154', 'user_name' => 'ddada', 'id_number' => ''],
//        ];
        $num = 0;//计数器
        if (empty($data) || !is_array($data)) {
            return $num;
        }
        $transaction = Yii::$app->db->beginTransaction();
        try {
            //查询电话时候再表里 没有插入返回id  有返回id  去关联表 查时候有没有 则插入
            foreach ($data as $k => $v) {

                $user = BasMember::find()->where(['phone' => $v['phone']])->asArray()->one();
                if (empty($user)) {
                    $model = new BasMember();//设置场景
                    $model->setScenario(BasMember::SCENARIOS_USER_INSERT);
                    $model->load($v, '');
                    $model->save();

                    $userId = $model->id;
                } else {
                    $userId = $user['id'];
                }

                //插入关联表
                $count = UserBranch::find()->where(['user_id' => $userId, 'br_id' => $brId])->count();

                if (empty($count)) {
                    $model2 = new UserBranch();
                    $model2->setScenario(UserBranch::SCENARIOS_BANNER_INSERT);
                    $model2->load([
                        'br_id' => $brId,
                        'user_id' => $userId,
                        'br_title' => $branchTitle,
                    ], '');

                    if ($model2->save()) {
                        $num++;
                    }
                }
            }
            $transaction->commit();
            return $num;
        } catch (Exception $e) {
            $transaction->rollBack();
            BaseHelper::Error($e->getMessage());
        }
    }

}
